/**
 * Created by yangxianming on 2018/1/5.
 */

//
//接口定义 都是以api开头 所需参数都通过方法传入
//
//获取项目列表, 需要加载主页项目列表，新增项目弹框中的项目列表
function apiGetProject(dofun, dofun_2){
    var data = {
        "action":"getProject"
    };

    var xmlHttp1 = new XMLHttpRequest();
    xmlHttp1.onreadystatechange = function(){
        if (xmlHttp1.readyState==4){
            if(xmlHttp1.status==200){
                var r = JSON.parse(xmlHttp1.response);
                if (r["apiStatus"] == "0") {
                    alert(r["errorMsg"])
                }
                if (r["apiStatus"] == "1"){
                    dofun(r["result"]);
                    dofun_2(r["result"]);
                }
            }
        }
    };
    xmlHttp1.open("POST", "/configuration/projectManager", true);
    xmlHttp1.send(JSON.stringify(data));
}

//查询用例
function apiQueryCase(dofun, projectName, caseName){
    var saveData = {"type":"3"};

    //获取项目名
    if (projectName != ""){
        saveData.projectName = projectName;
    }
    //获取关键字
    if (caseName != ""){
        saveData.caseName = caseName;
    }

    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("post", "/caseManager/queryCase", true);
    xmlHttp.onreadystatechange = function(){
        if (xmlHttp.readyState==4){
            if (xmlHttp.status==200){
                var r = JSON.parse(xmlHttp.response);
                if (r["apiStatus"] == "1"){
                    dofun(r["result"]);
                }else{
                    alert(r["errorMsg"]);
                }
            }
        }else{
            //alert("服务器异常1");
        }
    };
    xmlHttp.send(JSON.stringify(saveData));
}

//查询测试结果
function apiLoadReport(dofun, action, type, caseId, date){
    var saveData = "action=pyReport";

    //类型
    if (type != ""){
        saveData += "&type=" + type;
    }
    //用例id
    if (caseId != ""){
        saveData += "&caseId=" + caseId;
    }
    //date
    if (date != ""){
        saveData += "&date=" + date;
    }

    //if (saveData != ""){
    //    //去掉第一个符号
    //    saveData = saveData.substr(1, saveData.length);
    //}

    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("get", "/caseManager/loadReport?"+saveData, true);
    xmlHttp.onreadystatechange = function(){
        if (xmlHttp.readyState==4){
            if (xmlHttp.status==200){
                var r = JSON.parse(xmlHttp.response);
                if (r["apiStatus"] == "1"){
                    dofun(r["result"]);
                }else{
                    alert(r["errorMsg"]);
                }
            }else{
                alert("服务器异常");
            }
        }
    };
    xmlHttp.send();
}
//执行测试测试 参数为一组caseid
function apiRunCases(dofun, caseIdArrString, back302){
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("get", "/caseManager/runOtherCase?caseId=" + caseIdArrString + "&back302=" + back302, true);
    xmlHttp.onreadystatechange = function(){
        if (xmlHttp.readyState==4){
            if (xmlHttp.status==200){
                var r = JSON.parse(xmlHttp.response);
                if (r["apiStatus"] == "1"){
                    alert("测试已经提交，并开始测试");
                }
                if (r["apiStatus"] == "2"){
                    alert(r["result"]);
                }
            }else{
                alert("服务器异常");
            }
        }
    };
    xmlHttp.send();
}


//
//页面渲染 都是以draw开头
//
//加载主页面项目列表,
function drawLoadProjectList(data){
    var project = document.getElementById("project");
    var allData = ["全部项目"];
    for(var i = 0; i < data.length; i++){
        allData.push(data[i]);
    }
    loadSelectList(project, allData);
    project.onchange = function(){loadCases()};
    //这里同时加载case列表
    loadCases();
}
//加载添加用例悬浮层的项目列表
function drawTopDivProject(data){
    loadSelectList(document.getElementById("topDivProjects"), data);
}
//加载主界面用例列表
function drawLoadCase(data){
    //渲染界面 并 加载数据
    var tbody = document.getElementById("caseList").getElementsByTagName("tbody")[0];
    //清空所有行,保留抬头
    var firstTr = tbody.getElementsByTagName("tr")[0];
    tbody.innerText = "";
    tbody.appendChild(firstTr);

    //var testCases = [
    //    ["开放平台", "验证标题", "验证标题是否符合预期", "t1"],
    //    ["开放平台", "验证排序", "验证列表排序是否正确", "t2"]
    //];

    var testCases = data;
    for(var i = 0; i < testCases.length; i++){
        var tr = document.createElement("tr");
        //设置鼠标浮动效果
        tr.onmouseover = function(){
            this.style.backgroundColor = "#ffeaea";
        };
        tr.onmouseout = function(){
            this.style.backgroundColor = "";
        };

        //设置隐藏字段caseid
        tr.setAttribute("caseid", testCases[i][0]);
        //设置项目名
        var tdProName = document.createElement("td");
        tdProName.innerText = testCases[i][1];
        tr.appendChild(tdProName);
        //设置用例名
        var tdCaseName = document.createElement("td");
        tdCaseName.innerText = testCases[i][2];
        tr.appendChild(tdCaseName);
        //设置用例说明
        var tdCaseExplain = document.createElement("td");
        tdCaseExplain.innerText = testCases[i][3];
        tr.appendChild(tdCaseExplain);
        //调用的文件名
        var tdCaseFile = document.createElement("td");
        tdCaseFile.innerText = testCases[i][4];
        tr.appendChild(tdCaseFile);
        //是否跳过执行单选
        var tdJump = document.createElement("td");
        var inputIntd = document.createElement("input");
        inputIntd.className = "checkboxForTD";
        inputIntd.type = "checkbox";
        if(testCases[i][5] == 1){
            inputIntd.checked = "checked";
        }
        inputIntd.onclick = function(){updateCaseIsJump(this)};
        tdJump.appendChild(inputIntd);
        tr.appendChild(tdJump);

        //设置操作按钮
        var tdLast = document.createElement("td");
        var span = document.createElement("span");
        var span2 = document.createElement("span");
        var span3 = document.createElement("span");
        var span4 = document.createElement("span");
        span.setAttribute("class", "forTwoWord");
        span2.setAttribute("class", "forTwoWord");
        span3.setAttribute("class", "forTwoWord");
        span4.setAttribute("class", "forTwoWord");
        span.innerText = "编辑";
        span.onclick = function(){controlTopDivCase("createCase", "open", "编辑用例", this.parentNode.parentNode);};
        span2.innerText = "删除";
        span2.onclick = function(){deleteCase(this.parentNode.parentNode.getAttribute("caseid"));};
        span3.innerText = "运行";
        span3.onclick = function(){runCase(this.parentNode.parentNode.getAttribute("caseid"));};
        span4.innerText = "记录";
        span4.onclick = function(){testReport(this.parentNode.parentNode.getAttribute("caseid"));};
        tdLast.appendChild(span);
        tdLast.appendChild(span2);
        tdLast.appendChild(span3);
        tdLast.appendChild(span4);
        tr.appendChild(tdLast);
        //将一行加入body中
        tbody.appendChild(tr);
    }
}
//绘制测试记录弹出页面
function drawLoadReport(data){
    //type:用例类型  caseId 具体看testreport表
    var results = document.getElementById("resultList").getElementsByTagName("div")[0];
    results.innerText = "";
    //加载测试结果
    var listShell = document.createElement("div");
    listShell.style.width = "100%";
    listShell.style.marginLeft = "20px";
    results.appendChild(listShell);
    for(var indexBatchNo in data){
        var batchList = data[indexBatchNo];
        var oneBatchNo, oneBatchList;
        for(var k in batchList){
            oneBatchNo = k;
            oneBatchList = batchList[k];
        }
        var batchLine = document.createElement("div");
        var batchPLine = document.createElement("p");
        batchPLine.innerText = "批次号：" + k;
        batchLine.appendChild(batchPLine);
        listShell.appendChild(batchLine);

        for(var oneResultIndex in oneBatchList){
            var oneResult = oneBatchList[oneResultIndex];
            var aLine = document.createElement("div");
            aLine.style.marginLeft = "25px";
            aLine.style.width = "100%";
            aLine.style.cursor = "pointer";
            var name = oneResult[0];
            var isSuccess = oneResult[1];
            var createTime = oneResult[2];
            var resultId = oneResult[3];
            var testResult = oneResult[4];
            var expectResult = oneResult[5];

            var collapseHead = document.createElement("p");
            collapseHead.style.fontSize = "25px";
            collapseHead.innerText = "用例名：" + name + "；   测试时间：" + createTime;
            if(isSuccess == 1){
                collapseHead.style.color = "green";
            }
            if(isSuccess == -1){
                collapseHead.style.color = "red";
            }
            if(isSuccess == -2){
                collapseHead.style.color = "violet";
            }
            //渲染折叠数据 - 外
            collapseHead.setAttribute("data-toggle", "collapse");
            collapseHead.setAttribute("data-target", "#rID" + resultId);
            var detailDiv = document.createElement("div");
            detailDiv.setAttribute("id", "rID" + resultId);
            detailDiv.setAttribute("class", "collapse");
            aLine.appendChild(collapseHead);
            aLine.appendChild(detailDiv);
            listShell.appendChild(aLine);

            //渲染折叠数据 - 内
            var detailUl = document.createElement("ul");
            if (testResult == null || testResult == ""){
                continue
            }
            var detailLi_1 = document.createElement("li");
            var detailLi_2 = document.createElement("li");
            detailLi_1.style.width = "700px";
            detailLi_1.innerText = JSON.stringify(testResult);
            detailUl.appendChild(detailLi_1);
            detailLi_2.style.width = "700px";
            detailLi_2.innerText = JSON.stringify(expectResult);
            detailUl.appendChild(detailLi_2);
            detailDiv.appendChild(detailUl);
        }
    }
}

//
//页面调用 数据获取，接口层与渲染层的连接
//
//初始化数据 加载主页面项目列表，加载全部用例列表
function loadCasePageData(){
    apiGetProject(drawLoadProjectList, drawTopDivProject);
}
//加载用例
function loadCases(){
    //获取项目名
    var projectName = selectedText(document.getElementById("project"));
    if(projectName == "全部项目"){
        projectName = "";
    }
    //获取关键字
    var words = document.getElementById("words").value.trim();
    apiQueryCase(drawLoadCase, projectName, words);
}
//测试记录数据加载,测试记录弹出框中的查询
function loadResultData(){
    var date = document.getElementById("date").value;
    var batch = document.getElementById("batchNo").value;
    apiLoadReport(drawLoadReport, "3", "", date, batch);
}
//点击主页面的“所有记录”
function testAllReport(){
    var today = new Date().format("yyyy-MM-dd");
    document.getElementById("date").value = today;
    controlTopDivCase("testResult", "open", "测试记录");
    //loadResultData("3", "", today, "");
    apiLoadReport(drawLoadReport, "3", "", today, "");
}
//点击单条用例的 “记录”
function testReport(caseId){
    var today = new Date().format("yyyy-MM-dd");
    document.getElementById("date").value = today;
    controlTopDivCase("testResult", "open", "测试记录");
    //loadResultData("3", caseId, today, "");
    apiLoadReport(drawLoadReport, "3", caseId, today, "");
}
//用例查询 按键触发 样例代码
function keyboard(event){
    var e = event || window.event;
    if (e && e.keyCode ==13){
        var date = document.getElementById("date").value;
        //loadResultData("3", "", date);
    }
}
//生成链接
function showRunLink(){
    var urlPath = window.document.location.href;
    var docPath = window.document.location.pathname;
    var domain = urlPath.substring(0, urlPath.indexOf(docPath));
    var serverPath = domain + "/caseManager/runOtherCase?back302=1&domain302="+domain+"&needAlert=1&caseId=";
    var l = document.getElementById("caseList").getElementsByTagName("tbody")[0].getElementsByTagName("tr");
    var p = "";
    var le = l.length;
    for (var i = 0; i < le; i++){
        if(l[i].hasAttribute("caseid")){
            if(l[i].getElementsByTagName("input")[0].checked){
                //跳过isjump勾选的的数据
                continue;
            }
            p = p + l[i].getAttribute("caseid");
            p = p + ",";
        }
    }
    p = p.substring(0, p.length-1);
    prompt("双击复制链接", serverPath + p);

}
//caseReport页面触发接口 loadPage
function loadPage(){
    var batchNo = getQueryVariable("batchNo");
    var batchNoInput = document.getElementById("batchNo");
    batchNoInput.value = batchNo;
    loadResultData();
    var timer = setInterval(function(){
        var pList = document.getElementById("resultList").getElementsByTagName("p");
        var needBread = true;
        for(var i = 0; i < pList.length; i++){
            var oneP = pList[i];
            if(oneP.hasAttribute("data-toggle") && !oneP.hasAttribute("style")){
                needBread = false;
            }
        }
        if(needBread){
            clearInterval(timer);
        }
        loadResultData();
    }, 2000);
}
//单独执行用例
function runCase(caseId) {
    if (!confirm("开始跑测试喽？")) {
        return;
    }
    apiRunCases("", caseId, "0");
}
//执行一组用例
function runAll(){
    var l = document.getElementById("caseList").getElementsByTagName("tbody")[0].getElementsByTagName("tr");
    var p = "";
    var le = l.length;
    for (var i = 0; i < le; i++){
        if(l[i].hasAttribute("caseid")){
            if(l[i].getElementsByTagName("input")[0].checked){
                //跳过isjump勾选的的数据
                continue;
            }
            p = p + l[i].getAttribute("caseid");
            if (i < (le - 1)){
                p = p + ",";
            }
        }
    }
    runCase(p)
}


//
//
//旧代码
//
//
//删除用例
function deleteCase(caseId){
    if(!confirm("确认删除嘛？")){
        return;
    }
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("get", "/caseManager/delCase?caseId=" + caseId, true);
    xmlHttp.onreadystatechange = function(){
        if (xmlHttp.readyState==4){
            if (xmlHttp.status==200){
                var r = JSON.parse(xmlHttp.response);
                if (r["apiStatus"] == "1"){
                    loadCases();
                }else{
                    alert(r["errorMsg"]);
                }
            }else{
                alert("服务器异常");
            }
        }
    };
    xmlHttp.send();
}



//测试记录弹出层
function controlTopDivCase(whichWindow, mySwitch, text, trObject){
    var topDiv = document.getElementById(whichWindow);
    if (mySwitch == "open") {
        //设置页面抬头
        topDiv.getElementsByTagName("label")[0].innerText = text;
        //显示页面
        topDiv.style.marginTop = document.documentElement.scrollTop + "px";
        topDiv.style.display = "block";
    }

    //创建和编辑功能判断
    if (text == "添加用例"){
        //添加
        document.getElementById("topDivProjects").options[0].selected = true;
        document.getElementById("caseName").value = "";
        document.getElementById("describe").value = "";
        document.getElementById("saveButton").onclick = function(){saveCase()};
    }
    if (text == "编辑用例"){
        //编辑
        var td = trObject.getElementsByTagName("td");
        var projectSelect = document.getElementById("topDivProjects");
        document.getElementById("caseId").setAttribute("caseid", trObject.getAttribute("caseid"));
        for (var i = 0; i < projectSelect.options.length; i++) {
            if (projectSelect.options[i].text == td[0].innerText) {
                projectSelect.options[i].selected = true;
                break;
            }
        }
        document.getElementById("caseName").value = td[1].innerText;
        document.getElementById("describe").value = td[2].innerText;
        document.getElementById("scriptName").value = td[3].innerText;
        document.getElementById("saveButton").onclick = function(){updateCase()};
    }
    if (mySwitch == "close") topDiv.style.display = "none";
}

function updateCaseIsJump(isjumpOb){
    //更新isjump字段
    var id = isjumpOb.parentNode.parentNode.getAttribute("caseid");
    var data = {
        "id": id
    };
    if(isjumpOb.checked){
        data.isjump = "1";
    }else{
        data.isjump = "0";
    }
    updateCaseApi(data);
}

function updateCase(){
    //更新项目，脚本名，用例名，用例说明
    //{"projectName":"开放平台","caseName":"用例名字xx","describe":"描述xx","id":"1"}
    var paramsData = {
        "caseName":document.getElementById("scriptName").value.trim(),
        "params":""
    };

    var data = {
        "projectName": selectedText(document.getElementById("topDivProjects")),
        "caseName": document.getElementById("caseName").value.trim(),
        "describe": document.getElementById("describe").value.trim(),
        "data": paramsData,
        "id": document.getElementById("caseId").getAttribute("caseid")
    };
    updateCaseApi(data, 1);
}

function updateCaseApi(data, refreshPage){
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("post", "/caseManager/updateCase", true);
    xmlHttp.onreadystatechange = function(){
        if (xmlHttp.readyState==4){
            if (xmlHttp.status==200){
                var r = JSON.parse(xmlHttp.response);
                if (r["apiStatus"] == "1"){
                    controlTopDivCase('createCase', 'close', '');
                    if(refreshPage == 1){
                        loadCases(); //刷新列表
                    }
                }else{
                    alert(r["errorMsg"]);
                }

            }else{
                alert("服务器异常");
            }
        }
    };
    xmlHttp.send(JSON.stringify(data));
}


function saveCase(){
    var projectName = selectedText(document.getElementById("topDivProjects"));
    var caseName = document.getElementById("caseName").value.trim();
    var describe = document.getElementById("describe").value.trim();
    var scriptName = document.getElementById("scriptName").value.trim();

    var data = {
        "caseName": scriptName,
        "params": ""
    };

    var saveData = {
        "projectName": projectName,
        "caseName": caseName,
        "describe": describe,
        "data":data,
        "type": "3",
        "isdel": "0"
    };

    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("post", "/caseManager/addCase", true);
    xmlHttp.onreadystatechange = function(){
        if (xmlHttp.readyState==4){
            if (xmlHttp.status==200){
                var r = JSON.parse(xmlHttp.response);
                if (r["apiStatus"] == "1"){
                    controlTopDivCase('createCase', 'close', '');
                    loadCases(); //刷新列表
                }else{
                    alert(r["errorMsg"]);
                }

            }else{
                alert("服务器异常");
            }
        }
    };
    xmlHttp.send(JSON.stringify(saveData));
}


